<?php


namespace app\miniapp\controller;


use app\common\controller\Api;
use app\miniapp\model\MemberModel;

class Login extends Api
{
    protected $noNeedLogin = '*';
    //登录功能
    public function login()
    {
        $code = input('code');
        $appId = input('appid');
        $secret = input('secret');
        if (empty($code)) {
            $this->error('code不能为空');
        }
        if (empty($appId)) {
            $appId = 'wx5b9eb69f3665f849';
        }
        if (empty($secret)) {
            $secret = '312eb64a46d4d5df71ec6d16f82718da';
        }
//        $appId = 'wx5b9eb69f3665f849';
//        $secret = '312eb64a46d4d5df71ec6d16f82718da';
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$secret&js_code=$code&grant_type=authorization_code ";
        $result = curlRequest('GET', $url, 'json');
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            $this->error($result['errmsg']);
        }
        // 根据 openid 查询是否已经存在了
        $model = new MemberModel();
        $user = $model->where('openid', $result['openid'])->find();
        if ($user) {
            $user->session_key = $result['session_key'];
            $user->last_login_time = date('Y-m-d H:i:s');
            if ($user->save()) {
                $this->success('登录成功',[
                    'token' => create_token([
                        'id' => $user['id'],
                    ])
                ]);
            } else {
                $this->error('登录失败',[
                    'token' => ''
                ]);
            }

        } else {
            $model->openid = $result['openid'];
            $model->session_key = $result['session_key'];
            $model->create_time = date('Y-m-d H:i:s');
            if ($model->save()) {
                $this->success('登录成功',[
                    'token' =>  create_token([
                        'id' => $model->id,
                    ])
                ]);
            } else {
                $this->error('登录失败',[
                    'token' => ''
                ]);
            }
        }

    }

}